<template>
  <div class="designer-container">
    <div class="designer-header">
      <div class="logo">AI设计</div>
      <div class="tools">
        <el-button size="small" @click="saveDesign">保存</el-button>
        <el-button size="small" @click="exportDesign">导出</el-button>
        <el-button size="small" type="primary" @click="previewDesign">预览</el-button>
      </div>
    </div>
    
    <div class="designer-content">
      <!-- 左侧侧边栏 -->
      <div class="left-sidebar">
        <design-sidebar 
          @add-element="handleAddElement"
          @toggle-grid="toggleGrid"
          @toggle-ruler="toggleRuler"
          @color-change="setColor"
        />
      </div>
      
      <!-- 中间主内容区 -->
      <div class="main-content">
        <div class="canvas-container">
          <canvas ref="fabricCanvas" class="design-canvas"></canvas>
        </div>
      </div>
      
      <!-- 右侧属性栏 -->
      <div class="right-sidebar">
        <el-tabs v-model="activeTab">
          <el-tab-pane label="属性" name="properties">
            <div v-if="selectedObject" class="properties-panel">
              <design-property-panel
                :selected-object="selectedObject"
                @update-property="updateObjectProperty"
                @toggle-text-style="toggleTextStyle"
              />
            </div>
            <div v-else class="empty-hint">
              <p>请选择一个元素进行编辑</p>
            </div>
          </el-tab-pane>
          
          <el-tab-pane label="AI绘画" name="ai">
            <div class="ai-panel">
              <el-form label-position="top">
                <el-form-item label="提示词">
                  <el-input 
                    v-model="aiPrompt" 
                    type="textarea" 
                    rows="4" 
                    placeholder="描述你想要生成的图像..."
                  />
                </el-form-item>
                
                <el-form-item label="风格">
                  <el-select v-model="aiStyle" placeholder="选择风格">
                    <el-option label="写实" value="realistic" />
                    <el-option label="动漫" value="anime" />
                    <el-option label="油画" value="oil_painting" />
                    <el-option label="素描" value="sketch" />
                    <el-option label="水彩" value="watercolor" />
                  </el-select>
                </el-form-item>
                
                <el-form-item label="创造力">
                  <el-slider v-model="aiCreativity" :min="1" :max="10" />
                </el-form-item>
                
                <el-collapse>
                  <el-collapse-item title="高级设置">
                    <el-form-item label="尺寸">
                      <el-select v-model="aiSize" placeholder="选择尺寸">
                        <el-option label="512x512" value="512x512" />
                        <el-option label="768x768" value="768x768" />
                        <el-option label="1024x1024" value="1024x1024" />
                      </el-select>
                    </el-form-item>
                    
                    <el-form-item label="采样步数">
                      <el-slider v-model="aiSteps" :min="20" :max="150" />
                    </el-form-item>
                    
                    <el-form-item label="随机种子">
                      <el-input v-model="aiSeed" placeholder="留空为随机" />
                    </el-form-item>
                  </el-collapse-item>
                </el-collapse>
                
                <el-button type="success" :loading="aiGenerating" @click="generateAiImage">生成图像</el-button>
              </el-form>
              
              <div v-if="aiResult" class="ai-result">
                <img :src="aiResult" class="ai-image" alt="AI生成图像" />
                <el-button size="small" type="primary" @click="useAiImage">
                  使用此图像
                </el-button>
              </div>
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, nextTick } from 'vue';
import * as fabric from 'fabric';
import DesignSidebar from '@/modules/designer/components/sidebar/DesignSidebar.vue';
import DesignPropertyPanel from '@/modules/designer/components/property/PropertyPanel.vue';

// 页面状态
const activeTab = ref('properties');
const fabricCanvas = ref(null);
let canvas = null;

// 编辑器状态
const selectedObject = ref(null);
const selectedColor = ref('#FF5722');

// AI绘画状态
const aiPrompt = ref('');
const aiStyle = ref('realistic');
const aiCreativity = ref(7);
const aiSize = ref('512x512');
const aiSteps = ref(50);
const aiSeed = ref('');
const aiGenerating = ref(false);
const aiResult = ref('');

// 初始化画布
onMounted(async () => {
  await nextTick();
  canvas = new fabric.Canvas(fabricCanvas.value, {
    width: 800,
    height: 600,
    backgroundColor: '#ffffff'
  });
  
  // 设置选择事件监听
  canvas.on('selection:created', handleObjectSelected);
  canvas.on('selection:updated', handleObjectSelected);
  canvas.on('selection:cleared', handleSelectionCleared);
});

onUnmounted(() => {
  if (canvas) {
    canvas.dispose();
  }
});

// 处理选择事件
function handleObjectSelected(e) {
  selectedObject.value = canvas.getActiveObject();
  activeTab.value = 'properties';
}

function handleSelectionCleared() {
  selectedObject.value = null;
}

// 处理添加元素
function handleAddElement(type) {
  switch (type) {
    case 'rectangle':
      addRectangle();
      break;
    case 'circle':
      addCircle();
      break;
    case 'triangle':
      addTriangle();
      break;
    case 'text':
      addText();
      break;
    case 'brush':
      toggleBrush();
      break;
    case 'line':
      addLine();
      break;
  }
}

// 添加矩形
function addRectangle() {
  const rect = new fabric.Rect({
    left: 100,
    top: 100,
    width: 100,
    height: 100,
    fill: selectedColor.value,
    stroke: '#000000',
    strokeWidth: 1
  });
  
  canvas.add(rect);
  canvas.setActiveObject(rect);
}

// 添加圆形
function addCircle() {
  const circle = new fabric.Circle({
    left: 100,
    top: 100,
    radius: 50,
    fill: selectedColor.value,
    stroke: '#000000',
    strokeWidth: 1
  });
  
  canvas.add(circle);
  canvas.setActiveObject(circle);
}

// 添加三角形
function addTriangle() {
  const triangle = new fabric.Triangle({
    left: 100,
    top: 100,
    width: 100,
    height: 100,
    fill: selectedColor.value,
    stroke: '#000000',
    strokeWidth: 1
  });
  
  canvas.add(triangle);
  canvas.setActiveObject(triangle);
}

// 添加文本
function addText() {
  const text = new fabric.IText('输入文字', {
    left: 100,
    top: 100,
    fontFamily: 'Arial',
    fontSize: 24,
    fill: selectedColor.value
  });
  
  canvas.add(text);
  canvas.setActiveObject(text);
  activeTab.value = 'properties';
}

// 添加线条
function addLine() {
  const line = new fabric.Line([50, 50, 200, 200], {
    stroke: selectedColor.value,
    strokeWidth: 2
  });
  
  canvas.add(line);
  canvas.setActiveObject(line);
}

// 切换画笔模式
function toggleBrush() {
  canvas.isDrawingMode = !canvas.isDrawingMode;
  if (canvas.isDrawingMode) {
    canvas.freeDrawingBrush.color = selectedColor.value;
    canvas.freeDrawingBrush.width = 5;
  }
}

// 设置颜色
function setColor(color) {
  selectedColor.value = color;
  
  if (canvas.isDrawingMode) {
    canvas.freeDrawingBrush.color = color;
  }
  
  if (selectedObject.value) {
    if (selectedObject.value.type === 'text') {
      selectedObject.value.set('fill', color);
    } else {
      selectedObject.value.set('fill', color);
    }
    canvas.renderAll();
  }
}

// 更新对象属性
function updateObjectProperty(property, value) {
  if (!selectedObject.value) return;
  
  selectedObject.value.set(property, value);
  canvas.renderAll();
}

// 切换文本样式
function toggleTextStyle(property, value) {
  if (!selectedObject.value || !selectedObject.value.type.includes('text')) return;
  
  selectedObject.value.set(property, value);
  canvas.renderAll();
}

// 显示/隐藏网格
function toggleGrid() {
  // Grid implementation would go here
  console.log('Toggle grid');
}

// 显示/隐藏标尺
function toggleRuler() {
  // Ruler implementation would go here
  console.log('Toggle ruler');
}

// 保存设计
function saveDesign() {
  const json = canvas.toJSON();
  console.log('Save design:', json);
  // Here you would save to backend
}

// 导出设计
function exportDesign() {
  const dataURL = canvas.toDataURL({
    format: 'png',
    quality: 1
  });
  
  const link = document.createElement('a');
  link.href = dataURL;
  link.download = 'design.png';
  link.click();
}

// 预览设计
function previewDesign() {
  const dataURL = canvas.toDataURL();
  window.open(dataURL);
}

// AI生成图像
async function generateAiImage() {
  aiGenerating.value = true;
  
  try {
    // 模拟API调用
    console.log('AI generation parameters:', {
      prompt: aiPrompt.value,
      style: aiStyle.value,
      creativity: aiCreativity.value,
      size: aiSize.value,
      steps: aiSteps.value,
      seed: aiSeed.value || Math.floor(Math.random() * 1000000)
    });
    
    // 模拟延迟
    await new Promise(resolve => setTimeout(resolve, 2000));
    
    // 模拟结果
    aiResult.value = `https://picsum.photos/${aiSize.value.split('x')[0]}`;
  } catch (error) {
    console.error('AI generation failed:', error);
  } finally {
    aiGenerating.value = false;
  }
}

// 将AI生成的图像添加到设计中
function useAiImage() {
  if (!aiResult.value) return;
  
  fabric.Image.fromURL(aiResult.value, function(img) {
    // 根据画布大小调整图像大小
    const canvasWidth = canvas.width;
    const canvasHeight = canvas.height;
    const imgRatio = img.width / img.height;
    let newWidth, newHeight;
    
    if (imgRatio > canvasWidth / canvasHeight) {
      newWidth = canvasWidth * 0.8;
      newHeight = newWidth / imgRatio;
    } else {
      newHeight = canvasHeight * 0.8;
      newWidth = newHeight * imgRatio;
    }
    
    img.set({
      left: (canvasWidth - newWidth) / 2,
      top: (canvasHeight - newHeight) / 2,
      scaleX: newWidth / img.width,
      scaleY: newHeight / img.height
    });
    
    canvas.add(img);
    canvas.setActiveObject(img);
    canvas.renderAll();
    activeTab.value = 'properties';
  });
}
</script>

<style scoped>
.designer-container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  overflow: hidden;
}

.designer-header {
  height: 48px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 16px;
  background-color: #fafafa;
  border-bottom: 1px solid #e0e0e0;
}

.logo {
  font-size: 18px;
  font-weight: bold;
  color: #333;
}

.designer-content {
  display: flex;
  flex: 1;
  overflow: hidden;
}

.left-sidebar {
  width: 220px;
  border-right: 1px solid #e0e0e0;
  background-color: #f5f5f5;
  overflow-y: auto;
}

.main-content {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #e9e9e9;
  overflow: auto;
}

.canvas-container {
  position: relative;
}

.design-canvas {
  background-color: #fff;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.right-sidebar {
  width: 280px;
  border-left: 1px solid #e0e0e0;
  background-color: #f5f5f5;
  overflow-y: auto;
  padding: 16px;
}

.empty-hint {
  padding: 20px;
  text-align: center;
  color: #999;
}

.ai-result {
  margin-top: 16px;
  text-align: center;
}

.ai-image {
  max-width: 100%;
  margin-bottom: 8px;
  border-radius: 4px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}
</style>